/*
 * Copyright (C) 2011 CrystalRange
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.crystalrange;

import org.zkoss.zk.ui.Session;
import org.zkoss.zk.ui.Sessions;
import org.zkoss.zk.ui.event.Events;
import org.zkoss.zul.Treeitem;
import org.zkoss.zul.TreeitemRenderer;

public class MenuTreeRenderer implements TreeitemRenderer {

    public void render(Treeitem item, Object data, int i) throws Exception {
        if (data instanceof MenuFolderNode) {
            this.renderMenuFolderNode(item, (MenuFolderNode) data);
        }
        if (data instanceof MenuItemNode) {
            this.renderMenuItemNode(item, (MenuItemNode) data);
        }
    }
    
    private void renderMenuFolderNode(Treeitem item, MenuFolderNode menuFolderNode) throws Exception {
        item.setValue(menuFolderNode);
        item.setId("menuFolderNode" + menuFolderNode.getId());
        item.setLabel(menuFolderNode.getName());
        item.setTooltiptext(menuFolderNode.getDescription());
        item.setImage("/img/folder.png");
        item.addEventListener(Events.ON_OPEN, new MenuFolderListener(item));

        Session session = Sessions.getCurrent();
        if (session.getAttribute(item.getId()) != null) {
            item.setOpen((Boolean) session.getAttribute(item.getId()));
        }
    }

    private void renderMenuItemNode(Treeitem item, MenuItemNode menuItemNode) throws Exception {
        item.setValue(menuItemNode);
        item.setId("menuItemNode" + menuItemNode.getId());
        item.setLabel(menuItemNode.getCode() + " - " + menuItemNode.getName());
        item.setTooltiptext(menuItemNode.getDescription());
        item.setImage("/img/application.png");
    }
}
